import React, { useContext } from 'react'
import './ContextDemo.css'

const ThemeContext = React.createContext('light')

class ThemedButton extends React.Component {
  static contextType = ThemeContext
  render() {
    console.log(this.context)
    return <button style={{
      backgroundColor: this.context === 'light'
        ? 'white' : 'gray',
      color: this.context === 'light'
        ? 'black' : 'white'
    }}>
      按钮
    </button>
  }
}

function ThemedImage({src}) {
  return <ThemeContext.Consumer>
    {theme =>
      (<img src={src} style={{
        border: '1px solid black',
        padding: 10,
        backgroundColor: theme==='light' ?  'white' : 'black'
        }} alt=''/>
      )
    }
  </ThemeContext.Consumer>
}

function ThemedInput() {
  const theme = useContext(ThemeContext)
  return <input type='text' className={theme} />
}

function Content() {
  return (
    <div>
      <ThemedButton />
      <ThemedImage src='https://tva1.sinaimg.cn/large/008i3skNgy1gwq9rmf5o2j308r08rdfz.jpg' />
      <ThemedInput />
    </div>
  )
}

export default function ContextDemo() {
  return (
    <>
      <ThemeContext.Provider value='dark'>
        <h2>Context Demo</h2>
        <Content />
      </ThemeContext.Provider>
      <ThemedButton />
      <ThemedImage src='https://tva1.sinaimg.cn/large/008i3skNgy1gwq9rmf5o2j308r08rdfz.jpg' />
      <ThemedInput />
    </>

  )
}
